package cn.mystylefree.config;

import cn.mystylefree.po.Configuration;
import cn.mystylefree.po.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @program my-project-model
 * @description:
 * @author: lee
 * @create: 2022/06/15 08:50
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * <select id="selectList" resultType="cn.mystylefree.my_persistence_demo.domain.User">
     * select * from user
     * </select>
     *
     * @param inputStream
     * @throws DocumentException
     */
    public void parse(InputStream inputStream) throws DocumentException {
        Document read = new SAXReader().read(inputStream);
        //获取到了mapper节点 接下来获取select 标签
        Element rootElement = read.getRootElement();
        List<Element> selectNodes = rootElement.selectNodes("//select");
        /*没过element就是
        <select id="selectList" resultType="cn.mystylefree.my_persistence_demo.domain.User">
            select * from user
        </select>*/
        String namespace = rootElement.attributeValue("namespace");

        for (Element node : selectNodes) {
            String id = node.attributeValue("id");
            String resultType = node.attributeValue("resultType");
            String parameterType = node.attributeValue("parameterType");
            //sql语句 文本信息
            String sqlText = node.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlText);
            //唯一标识
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
